package com.zoe.onelink.logging.trace.autoconfigure;

import brave.Span;
import brave.Tracing;
import cn.hutool.core.util.StrUtil;
import com.zoe.onelink.common.constant.TraceSpanConstant;
import com.zoe.onelink.logging.trace.redis.OnelinkCommandLatencyCollector;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import io.lettuce.core.tracing.BraveTracing;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.sleuth.instrument.redis.TraceRedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ClientResources.class, Tracing.class})
@AutoConfigureBefore(TraceRedisAutoConfiguration.class)
public class OnelinkTraceRedisAutoConfiguration {

    @Bean(destroyMethod = "shutdown")
    @ConditionalOnProperty(name = "spring.sleuth.redis.enabled", matchIfMissing = false)
    public DefaultClientResources lettuceClientResources(Environment env, Tracing braveTracing) {
        String serviceName = StrUtil.blankToDefault(env.getProperty("spring.sleuth.redis.remoteServiceName"), "redis");
        BraveTracing tracing = BraveTracing.builder().tracing(braveTracing)
                .includeCommandArgsInSpanTags(true)
                .serviceName(serviceName)
                .spanCustomizer(this::setTraceSpanInfo)
                .build();

        return DefaultClientResources.builder()
                .tracing(tracing)
                .commandLatencyCollector(new OnelinkCommandLatencyCollector())
                .build();
    }

    /**
     * 设置链路节点信息
     */
    private Span setTraceSpanInfo(Span span) {
        return span.tag(TraceSpanConstant.LOG_TYPE, TraceSpanConstant.LogType.REDIS);
    }


}
